package com.ruoyi.channel.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.ruoyi.channel.domain.ChannelApply;
import com.ruoyi.channel.domain.ChannelMerchants;
import com.ruoyi.channel.mapper.ChannelApplyMapper;
import com.ruoyi.channel.mapper.ChannelMerchantsMapper;
import com.ruoyi.channel.service.IChannelApplyService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.config.util.file.AliOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 渠道商审核Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-09
 */
@Service
public class ChannelApplyServiceImpl implements IChannelApplyService {
    @Autowired
    private ChannelApplyMapper channelApplyMapper;
    @Resource
    private ChannelMerchantsMapper channelMerchantsMapper;
    @Resource
    private AliOSSUtil aliOSSUtil;

    /**
     * 查询渠道商审核
     *
     * @param id 渠道商审核主键
     * @return 渠道商审核
     */
    @Override
    public ChannelApply selectChannelApplyById(Long id) {
        return channelApplyMapper.selectChannelApplyById(id);
    }

    /**
     * 查询渠道商审核列表
     *
     * @param channelApply 渠道商审核
     * @return 渠道商审核
     */
    @Override
    public List<ChannelApply> selectChannelApplyList(ChannelApply channelApply) {
        return channelApplyMapper.selectChannelApplyList(channelApply);
    }

    /**
     * 新增渠道商审核
     *
     * @param channelApply 渠道商审核
     * @return 结果
     */
    @Override
    public int insertChannelApply(ChannelApply channelApply) {
        channelApply.setCreateTime(DateUtils.getNowDate());
        return channelApplyMapper.insertChannelApply(channelApply);
    }

    /**
     * 修改渠道商审核
     *
     * @param channelApply 渠道商审核
     * @return 结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int updateChannelApply(ChannelApply channelApply) throws IOException {
        if (channelApply.getAuditStatus() == 1) {
            String userInvitationCode = channelApplyMapper.selectPartnerUserByTel(channelApply.getPartnerTel());
            Integer updated = channelApplyMapper.updateUserIdentity(channelApply.getUserId(), 2, userInvitationCode);
            if (updated == 0) {
                throw new RuntimeException("审核失败");
            }
            String invitationCode = channelApplyMapper.selectUserInvitetionCode(channelApply.getUserId());
            ChannelMerchants channelMerchants = new ChannelMerchants();
            channelMerchants.setUserId(channelApply.getUserId());
            channelMerchants.setChannelName(channelApply.getName());
            channelMerchants.setChannelTel(channelApply.getTel());
            channelMerchants.setChannelType(channelApply.getChannelName());
            String text = String.format("https://www.xishidaojia.net/#/?userInvitedCode=%s&loginType=%s",invitationCode,3);
            channelMerchants.setChannelMerchantsInvitedQrcode(getQRCodeImage(text,350,350));

            channelMerchants.setChannelMerchantsInvitationCode(invitationCode);
            channelMerchants.setChannelMerchantsInvitedCode(userInvitationCode);
            channelMerchantsMapper.insertChannelMerchants(channelMerchants);

        }
        channelApply.setUpdateTime(DateUtils.getNowDate());
        return channelApplyMapper.updateChannelApply(channelApply);
    }


    public String getQRCodeImage(String text, Integer width, Integer height) throws IOException {
        // 生成唯一文件名并指定为 PNG 格式
        String uniqueFileName = System.currentTimeMillis() + ".png";
        // 确保 QrCodeUtil.generate 支持 PNG 格式（这通常是默认的）
        BufferedImage generate = QrCodeUtil.generate(text, width, height);
        // 假设 aliOSSUtil.uploadFile 支持 PNG 格式
        return aliOSSUtil.uploadFile(bufferedImageToInputStream(generate), uniqueFileName);
    }

    private InputStream bufferedImageToInputStream(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos); // 可以根据需要更改为jpg或其他格式
        byte[] imageBytes = baos.toByteArray();
        return new ByteArrayInputStream(imageBytes);
    }

    /**
     * 批量删除渠道商审核
     *
     * @param ids 需要删除的渠道商审核主键
     * @return 结果
     */
    @Override
    public int deleteChannelApplyByIds(Long[] ids) {
        return channelApplyMapper.deleteChannelApplyByIds(ids);
    }

    /**
     * 删除渠道商审核信息
     *
     * @param id 渠道商审核主键
     * @return 结果
     */
    @Override
    public int deleteChannelApplyById(Long id) {
        return channelApplyMapper.deleteChannelApplyById(id);
    }
}
